package cn.ecpay.unionpay.settle.notify;

import cn.ecpay.unionpay.settle.Common.DateUtil;
import cn.ecpay.unionpay.settle.dao.LaizhangDao;
import cn.ecpay.unionpay.settle.entity.db.TPvLaiZhangNotify;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 来账通知处理
 * Created by zhaoyanzeng on 2018/11/6.
 */
@Component
public class LaiZhangNotify {

    @Resource
    private LaizhangDao laizhangDao;

    public void LaiZhangNotify(Map<String,String> reqParam)
            throws ServletException, IOException {
        LogUtil.writeLog("来账接收来账通知开始");
        TPvLaiZhangNotify laiZhangNotify = convertReturnMoney(reqParam);

        LogUtil.printRequestLog(reqParam);
        if (!FsasService.validate(reqParam, CommonBase.encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            laiZhangNotify.setNotifyValidate("0");
        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            laiZhangNotify.setNotifyValidate("1");
            String respCode = reqParam.get("respCode");
            LogUtil.writeLog("respCode=" + respCode);
        }
        try {
            LogUtil.writeLog("保存来账通知");
            laizhangDao.insert(laiZhangNotify);
            LogUtil.writeLog("保存来账通知成功");
        } catch (DBException e) {
            LogUtil.writeLog("保存来账通知失败");
            e.printStackTrace();
        }
        LogUtil.writeLog("接收来账通知结束");
    }

    private TPvLaiZhangNotify convertReturnMoney(Map<String, String> reqParam) {
        TPvLaiZhangNotify laiZhangNotify = new TPvLaiZhangNotify();
        laiZhangNotify.setTxnNo(reqParam.get("txnNo"));
        laiZhangNotify.setTxnType(reqParam.get("txnType"));
        laiZhangNotify.setAcqInsCode(reqParam.get("acqInsCode"));
        laiZhangNotify.setTxnDate(reqParam.get("txnDate"));
        laiZhangNotify.setPayerBankNo(reqParam.get("payerBankNo"));
        laiZhangNotify.setPayerAcctNo(reqParam.get("payerAcctNo"));
        laiZhangNotify.setPayerAcctName(reqParam.get("payerAcctName"));
        laiZhangNotify.setPayeeAcctNo(reqParam.get("payeeAcctNo"));
        laiZhangNotify.setPayeeAcctName(reqParam.get("payeeAcctName"));
        laiZhangNotify.setCurrencyCode(reqParam.get("currencyCode"));
        laiZhangNotify.setTxnAmt(reqParam.get("txnAmt"));
        laiZhangNotify.setPayeeAcctBal(reqParam.get("payeeAcctBal"));
        laiZhangNotify.setAcctDate(reqParam.get("acctDate"));
        laiZhangNotify.setRemark(reqParam.get("remark"));
        laiZhangNotify.setAcctDate(reqParam.get("acctDate"));
        laiZhangNotify.setCreateTime(DateUtil.getDateTo19(new Date()));
        return laiZhangNotify;
    }
}
